<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${fileName}">Markdown 预览</title>

    <script th:src="@{/lib/marked/marked.min.js}"></script>
    <script th:src="@{/lib/marked/highlight.min.js}"></script>

    <style>
        :root {
            --color-primary: #165dff;
            --color-text-1: #e6e6e6;
            --color-text-2: #b3b3b3;
            --color-text-3: #808080;
            --color-bg-1: #1a1a1a;
            --color-bg-2: #000000;
            --color-border: #333333;
            --color-fill-2: #2a2a2a;
            --color-danger: #f53f3f;
            --color-code-bg: #2d2d2d;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Inter, -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "noto sans", "Microsoft YaHei", "SimSun", sans-serif;
            background: var(--color-bg-2);
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            color: var(--color-text-1);
            user-select: text; /* Allow text selection for markdown */
        }

        .header {
            height: 48px;
            background: var(--color-bg-1);
            border-bottom: 1px solid var(--color-border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
            flex-shrink: 0;
            user-select: none;
        }

        .file-name {
            font-size: 14px;
            font-weight: 500;
            color: var(--color-text-1);
        }

        .close-btn {
            cursor: pointer;
            padding: 8px;
            border-radius: 4px;
            transition: background 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .close-btn:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .wrapper {
            display: flex;
            flex: 1;
            overflow: hidden;
            position: relative;
        }

        /* Sidebar */
        .toc-sidebar {
            width: 260px;
            background: var(--color-bg-1);
            border-right: 1px solid var(--color-border);
            overflow-y: auto;
            padding: 20px;
            flex-shrink: 0;
            display: flex;
            flex-direction: column;
        }

        .toc-title {
            font-size: 14px;
            font-weight: bold;
            color: var(--color-text-1);
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid var(--color-border);
        }

        .toc-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .toc-list li {
            margin-bottom: 4px;
        }

        .toc-list a {
            display: block;
            padding: 6px 8px;
            color: var(--color-text-2);
            text-decoration: none;
            font-size: 13px;
            border-radius: 2px;
            transition: all 0.2s;
            line-height: 1.4;
        }

        .toc-list a:hover {
            background-color: var(--color-fill-2);
            color: var(--color-text-1);
        }

        .toc-list a.active {
            background-color: rgba(22, 93, 255, 0.2);
            color: #4080ff;
            font-weight: 500;
        }

        .toc-h1 {
            padding-left: 8px;
        }

        .toc-h2 {
            padding-left: 20px;
        }

        .toc-h3 {
            padding-left: 32px;
        }

        /* Content */
        .container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            justify-content: center;
        }

        .markdown-body {
            background: var(--color-bg-1);
            padding: 40px 60px;
            border-radius: 4px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
            width: 100%;
            max-width: 900px;
            min-height: fit-content;
            color: var(--color-text-1);
        }

        /* Markdown Dark Theme Overrides */
        .markdown-body h1, .markdown-body h2, .markdown-body h3,
        .markdown-body h4, .markdown-body h5, .markdown-body h6 {
            color: var(--color-text-1);
            border-bottom-color: var(--color-border);
        }

        .markdown-body a {
            color: #4080ff;
        }

        .markdown-body blockquote {
            color: var(--color-text-2);
            border-left-color: var(--color-border);
        }

        .markdown-body hr {
            background-color: var(--color-border);
        }

        .markdown-body table tr {
            background-color: var(--color-bg-1);
            border-top-color: var(--color-border);
        }

        .markdown-body table tr:nth-child(2n) {
            background-color: var(--color-fill-2);
        }

        .markdown-body table th, .markdown-body table td {
            border-color: var(--color-border);
        }

        .markdown-body code {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .markdown-body pre {
            background-color: var(--color-code-bg);
        }

        /* Loading & Error */
        .loading-container, .error-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            width: 100%;
            color: var(--color-text-3);
            position: absolute;
            top: 0;
            left: 0;
            background: var(--color-bg-2);
            z-index: 10;
        }

        .error-container {
            display: none;
            text-align: center;
        }

        .spinner {
            width: 32px;
            height: 32px;
            border: 3px solid rgba(255, 255, 255, 0.1);
            border-top-color: var(--color-primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 16px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .error-title {
            font-size: 16px;
            font-weight: 500;
            color: var(--color-text-1);
            margin-bottom: 8px;
        }

        @media (max-width: 1024px) {
            .markdown-body {
                padding: 30px 40px;
            }
        }

        @media (max-width: 768px) {
            .toc-sidebar {
                display: none;
            }

            .markdown-body {
                padding: 20px;
            }
        }

        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-thumb {
            background: #444;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }
    </style>
</head>
<body>
<div class="header">
    <span class="file-name" th:text="${fileName}">Markdown 预览</span>
    <div class="close-btn" onclick="window.close()" title="关闭">
        <svg width="24" height="24" viewBox="0 0 48 48" fill="none">
            <path d="M14 14L34 34" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M14 34L34 14" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
    </div>
</div>

<div class="wrapper">
    <!-- Sidebar -->
    <div class="toc-sidebar" id="sidebar">
        <div class="toc-title">目录</div>
        <ul class="toc-list" id="toc"></ul>
    </div>

    <!-- Content -->
    <div class="container" id="scroll-container">
        <div class="markdown-body" id="content"></div>
    </div>

    <!-- Loading -->
    <div class="loading-container" id="loading">
        <div class="spinner"></div>
        <div>渲染中...</div>
    </div>

    <!-- Error -->
    <div id="error" class="error-container">
        <div class="error-title">加载失败</div>
        <div class="error-desc" id="error-msg">文件内容获取失败</div>
    </div>
</div>

<script th:inline="javascript">
    const streamUrl = /*[[${streamUrl}]]*/ '';

    function init() {
        if (typeof marked === 'undefined') {
            showError('Marked.js 资源加载失败');
            return;
        }

        marked.setOptions({
            breaks: true,
            gfm: true,
            highlight: function (code, lang) {
                if (typeof hljs !== 'undefined' && lang) {
                    try {
                        if (hljs.getLanguage(lang)) {
                            return hljs.highlight(code, {language: lang}).value;
                        }
                    } catch (e) {
                        console.warn('代码高亮失败:', e);
                    }
                }
                return code;
            }
        });

        fetch(streamUrl)
            .then(res => {
                if (!res.ok) throw new Error('HTTP ' + res.status);
                return res.text();
            })
            .then(markdown => {
                const html = marked.parse(markdown);
                document.getElementById('content').innerHTML = html;

                // Hide loading
                document.getElementById('loading').style.display = 'none';

                if (typeof hljs !== 'undefined') {
                    document.querySelectorAll('pre code').forEach(block => {
                        if (typeof hljs.highlightElement === 'function') {
                            hljs.highlightElement(block);
                        } else if (typeof hljs.highlightBlock === 'function') {
                            hljs.highlightBlock(block);
                        }
                    });
                }

                generateTOC();
            })
            .catch(err => {
                showError(err.message);
            });
    }

    function showError(msg) {
        document.getElementById('loading').style.display = 'none';
        document.getElementById('error').style.display = 'flex';
        document.getElementById('error-msg').textContent = msg;
        document.getElementById('sidebar').style.display = 'none';
        document.getElementById('content').style.display = 'none';
    }

    function generateTOC() {
        const content = document.getElementById('content');
        const toc = document.getElementById('toc');
        const headings = content.querySelectorAll('h1, h2, h3');

        if (headings.length === 0) {
            toc.innerHTML = '<li style="color: var(--color-text-3); font-size: 12px; padding: 8px;">暂无目录</li>';
            return;
        }

        headings.forEach((heading, index) => {
            const id = 'heading-' + index;
            heading.id = id;

            const li = document.createElement('li');
            const a = document.createElement('a');
            a.href = '#' + id;
            a.textContent = heading.textContent;
            a.className = 'toc-' + heading.tagName.toLowerCase();

            a.addEventListener('click', (e) => {
                e.preventDefault();
                heading.scrollIntoView({behavior: 'smooth', block: 'start'});

                // Update active state immediately
                document.querySelectorAll('.toc-list a').forEach(link => link.classList.remove('active'));
                a.classList.add('active');
            });

            li.appendChild(a);
            toc.appendChild(li);
        });

        // Scroll spy
        const scrollContainer = document.getElementById('scroll-container');
        let isScrolling = false;
        scrollContainer.addEventListener('scroll', () => {
            if (isScrolling) return;
            isScrolling = true;
            requestAnimationFrame(() => {
                updateActiveTOC();
                isScrolling = false;
            });
        });
    }

    function updateActiveTOC() {
        const headings = document.querySelectorAll('.markdown-body h1, .markdown-body h2, .markdown-body h3');
        const tocLinks = document.querySelectorAll('.toc-list a');

        let current = null;
        for (let i = 0; i < headings.length; i++) {
            const heading = headings[i];
            const rect = heading.getBoundingClientRect();
            if (rect.top > 0 && rect.top < window.innerHeight / 3) {
                current = i;
                break;
            }
            if (rect.top <= 0) {
                current = i;
            }
        }

        tocLinks.forEach((link, index) => {
            link.classList.toggle('active', index === current);
        });
    }

    // Disable context menu
    document.addEventListener('contextmenu', (e) => {
        e.preventDefault();
    });

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
</script>
</body>
</html>